<?

if (!empty($_GET['hectad']) && preg_match('/^(\w{1,2}\d)(\d)$/',$_GET['hectad'],$m)) {
	$hectad_like = $m[1].'_'.$m[2].'_';
	$sql['wheres'][] = "grid_reference LIKE ".dbQuote($hectad_like);
	
	$link = linktoself(array('delete'=>'hectad'));
	print "<div class=\"filter\">Where <b>hectad={$_GET['hectad']}</b>. [<a href=\"$link\">remove filter</a>]</div>";
	print "<input type=hidden name=hectad value=\"".he($_GET['hectad'])."\">";
	$opt['filtered'] = 1;
	
} elseif (!empty($_GET['myriad']) && preg_match('/^\w{1,2}$/',$_GET['myriad'])) {
	$sql['wheres'][] = "grid_reference LIKE ".dbQuote($_GET['myriad'].'%');
	
	$link = linktoself(array('delete'=>'myriad'));
	print "<div class=\"filter\">Where <b>myriad={$_GET['myriad']}</b>. [<a href=\"$link\">remove filter</a>]</div>";
	print "<input type=hidden name=myriad value=\"".he($_GET['myriad'])."\">";
	$opt['filtered'] = 1;
} 

if (!empty($_GET['gridref']) && preg_match('/^[\w]{5,7}$/',$_GET['gridref'])) {
	$sql['wheres'][] = "grid_reference = ".dbQuote($_GET['gridref']);
	
	$link = linktoself(array('delete'=>'gridref'));
	print "<div class=\"filter\">In <b>{$_GET['gridref']}</b>. [<a href=\"$link\">remove filter</a>]</div>";
	print "<input type=hidden name=gridref value=\"".he($_GET['gridref'])."\">";
	$opt['filtered'] = 1;
}

if (!empty($_GET['category']) && preg_match('/^[\w ]+$/',$_GET['category'])) {
	$sql['wheres'][] = "imageclass = ".dbQuote($_GET['category']);
	
	$link = linktoself(array('delete'=>'category'));
	print "<div class=\"filter\">Where <b>category={$_GET['category']}</b>. [<a href=\"$link\">remove filter</a>]</div>";
	print "<input type=hidden name=category value=\"".he($_GET['category'])."\">";
	$opt['filtered'] = 1;
}

if (!empty($_GET['canonical']) && preg_match('/^[\w ]+$/',$_GET['canonical'])) {
	$sql['tables']['cc'] = "INNER JOIN geograph_live.category_canonical AS cc USING (imageclass)";
	$sql['wheres'][] = "canonical = ".dbQuote($_GET['canonical']);
	
	$link = linktoself(array('delete'=>'canonical'));
	print "<div class=\"filter\">Where <b>canonical={$_GET['canonical']}</b>. [<a href=\"$link\">remove filter</a>]</div>";
	print "<input type=hidden name=canonical value=\"".he($_GET['canonical'])."\">";
	$opt['filtered'] = 1;
}

if (!empty($_GET['mod']) && preg_match('/^[\w ]+$/',$_GET['mod'])) {
	$sql['wheres'][] = "moderation_status = ".dbQuote($_GET['mod']);
	
	$link = linktoself(array('delete'=>'category'));
	print "<div class=\"filter\">Where <b>moderation={$_GET['mod']}</b>. [<a href=\"$link\">remove filter</a>]</div>";
	print "<input type=hidden name=mod value=\"".he($_GET['mod'])."\">";
	$opt['filtered'] = 1;
}

if (!empty($_GET['bi_id'])) {
	if ($row = getRow("SELECT user_id,realname FROM geograph_live.gridimage_search WHERE user_id = ".intval($_GET['bi_id'])." LIMIT 1")) {
		$sql['wheres'][] = "user_id = ".intval($_GET['bi_id']);
		$link = linktoself(array('delete'=>'bi_id'));
		print "<div class=\"filter\">By <b>".he($row['realname'])."</b>. [<a href=\"$link\">remove filter</a>";
		
		print " | <a href=\"http://www.geograph.org.uk/profile/{$row['user_id']}\"><b>Geograph British Isles Profile</b></a>";
		
		print "]</div>";
		
		print "<input type=hidden name=bi_id value=\"".he($_GET['bi_id'])."\">";
		$opt['filtered'] = 1;
	}
} elseif (!empty($_GET['user_id'])) {
	if ($row = getRow("SELECT realname,geo_bi_id,geo_de_id FROM `user` WHERE user_id = ".intval($_GET['user_id']))) {
		$sql['wheres'][] = "user_id = ".intval($row['geo_bi_id']);
		$link = linktoself(array('delete'=>'user_id'));
		print "<div class=\"filter\">By <b>".he($row['realname'])."</b>. [<a href=\"$link\">remove filter</a>";
		
		if ($row['geo_bi_id'])
			print " <a href=\"http://www.geograph.org.uk/profile/{$row['geo_bi_id']}\"><b>Geograph British Isles Profile</b></a>";
		if ($row['geo_de_id'])
			print " <a href=\"http://geo-en.hlipp.de/profile/{$row['geo_bi_id']}\">Geograph Germany Profile</a>";
		
		print "]</div>";
		
		print "<input type=hidden name=bi_id value=\"".he($_GET['bi_id'])."\">";
		$opt['filtered'] = 1;
	}
}
if (!empty($_GET['snippet_id'])) {
        if ($row2 = getRow("SELECT snippet_id,title FROM geograph_live.snippet WHERE enabled = 1 AND `snippet_id` = ".dbQuote($_GET['snippet_id']))) {
                $sql['tables']['g2s'] = "INNER JOIN geograph_live.gridimage_snippet AS g2s USING (gridimage_id)";
                $sql['wheres'][] = "g2s.snippet_id = ".$row2['snippet_id'];
                $link = linktoself(array('delete'=>'snippet_id'));
                print "<div class=\"filter\">Using <b><a href=\"http://www.geograph.org.uk/snippet/{$row2['snippet_id']}\">".he($row2['title'])."</a></b> shared description. [<a href=\"$link\">remove filter</a>]</div>";
                print "<input type=hidden name=snippet_id value=\"".he($_GET['snippet_id'])."\">";
		$opt['filtered'] = 1;
        }
}
if (!empty($_GET['tag_id'])) {
        if ($row2 = getRow("SELECT tag_id,prefix,tag,display FROM tag WHERE `tag_id` = ".dbQuote($_GET['tag_id']))) {
                $sql['tables']['g2t'] = "INNER JOIN p2.gridimage2tag{$portal_id}_bi AS g2t USING (gridimage_id)";
                $sql['wheres'][] = "g2t.tag_id = ".$row2['tag_id'];
                $link = linktoself(array('delete'=>'tag_id'));
                print "<div class=\"filter\">Using <b>".he($row2['display'])."</a></b> tag. [<a href=\"$link\">remove filter</a>]</div>";
                print "<input type=hidden name=tag_id value=\"".he($_GET['tag_id'])."\">";
		$opt['filtered'] = 1;
        }
}
if (!empty($_GET['tag'])) {
        if ($row2 = getRow("SELECT tag_id,prefix,tag,display FROM tag WHERE `display` = ".dbQuote($_GET['tag']))) {
                $sql['tables']['g2t'] = "INNER JOIN p2.gridimage2tag{$portal_id}_bi AS g2t USING (gridimage_id)";
                $sql['wheres'][] = "g2t.tag_id = ".$row2['tag_id'];
                $link = linktoself(array('delete'=>'tag'));
                print "<div class=\"filter\">Using <b>".he($row2['display'])."</a></b> tag. [<a href=\"$link\">remove filter</a>]</div>";
                print "<input type=hidden name=tag value=\"".he($_GET['tag'])."\">";
		$opt['filtered'] = 1;
        }
}


if (!empty($_GET['term'])) {
        if ($row2 = getRow("SELECT term FROM geograph_live.gridimage_term WHERE `term` = ".dbQuote($_GET['term'])." LIMIT 1")) {
                $sql['tables'][] = "INNER JOIN geograph_live.gridimage_term AS gt USING (gridimage_id)";
                $sql['wheres'][] = "gt.term = ".dbQuote($row2['term']);
                $link = linktoself(array('delete'=>'term'));
                print "<div class=\"filter\">tagged with <b>".he($row2['term'])."</b>. [<a href=\"$link\">remove filter</a>]</div>";
                print "<input type=hidden name=term value=\"".he($_GET['term'])."\">";
		$opt['filtered'] = 1;
        }
}

if (!empty($_GET['cluster'])) {
        if ($row2 = getRow("SELECT label FROM geograph_live.gridimage_group WHERE `label` = ".dbQuote($_GET['cluster'])." LIMIT 1")) {
                $sql['tables'][] = "INNER JOIN geograph_live.gridimage_group AS gg USING (gridimage_id)";
                $sql['wheres'][] = "gg.label = ".dbQuote($row2['label']);
                $link = linktoself(array('delete'=>'cluster'));
                print "<div class=\"filter\">tagged with <b>".he($row2['label'])."</b>. [<a href=\"$link\">remove filter</a>]</div>";
                print "<input type=hidden name=cluster value=\"".he($_GET['cluster'])."\">";
		$opt['filtered'] = 1;
        }
}

if (!empty($_GET['cluster2'])) {
        if ($row2 = getRow("SELECT label FROM gridimage_group WHERE `label` = ".dbQuote($_GET['cluster2'])." LIMIT 1")) {
                $sql['tables'][] = "INNER JOIN gridimage_group AS gg USING (gridimage_id)";
                $sql['wheres'][] = "gg.label = ".dbQuote($row2['label']);
                $sql['wheres'][] = "gg.portal_id = $portal_id";
                $link = linktoself(array('delete'=>'cluster2'));
                print "<div class=\"filter\">tagged with <b>".he($row2['label'])."</b>. [<a href=\"$link\">remove filter</a>]</div>";
                print "<input type=hidden name=cluster2 value=\"".he($_GET['cluster2'])."\">";
		$opt['filtered'] = 1;
        }
}

if (isset($_GET['recent'])) {
	
	$sql['wheres'][] = "created > DATE_SUB(NOW(),INTERVAL 30 DAY)";
	
	$link = linktoself(array('delete'=>'recent'));
	print "<div class=\"filter\">Added in the <b>last 30 days</b>. [<a href=\"$link\">remove filter</a>]</div>";
	print "<input type=hidden name=recent value=\"1\">";
	$opt['filtered'] = 1;
}

if (isset($_GET['age'])) {
	
	$link = linktoself(array('delete'=>'age'));
	$y = abs(intval($_GET['age']));
	if ($_GET['age'] > 0) {
		$sql['wheres'][] = "imagetaken > DATE_SUB(NOW(),INTERVAL $y YEAR)";
	
		print "<div class=\"filter\">Taken in the <b>last $y year(s)</b>. [<a href=\"$link\">remove filter</a>]</div>";
	} else {
		
		$sql['wheres'][] = "imagetaken < DATE_SUB(NOW(),INTERVAL $y YEAR)";
	
		print "<div class=\"filter\">Taken over <b>$y year(s) ago</b>. [<a href=\"$link\">remove filter</a>]</div>";
	}
	print "<input type=hidden name=age value=\"".he($_GET['age'])."\">";
	$opt['filtered'] = 1;
}

if (!empty($_GET['taken_start']) || !empty($_GET['taken_end']) ) {

	$start = $end = 0;
	
	if (preg_match('/^(\d{4})\/(\d{2})$/',$_GET['taken_start'],$m)) {
		$start = "{$m[1]}-{$m[2]}-00";
	} elseif (preg_match('/^(\d{4})$/',$_GET['taken_start'],$m)) {
		$start = "{$m[1]}-00-00";
	}
	if (preg_match('/^(\d{4})\/(\d{2})$/',$_GET['taken_end'],$m)) {
		$end = "{$m[1]}-{$m[2]}-31";
	} elseif (preg_match('/^(\d{4})$/',$_GET['taken_end'],$m)) {
		$end = "{$m[1]}-12-31";
	}

	if ($_GET['taken_start'] == $_GET['taken_end']) {
		//special case!
		
		$taken = str_replace('-00','',$start);
		
		$sql['wheres'][] = "imagetaken LIKE '$taken%'";
			
		$link = linktoself(array('delete'=>array('taken_start','taken_end')));
		print "<div class=\"filter\">Taken in <b>$taken</b>. [<a href=\"$link\">remove filter</a>]</div>";
		#print "<input type=hidden name=taken_start value=\"".he($_GET['taken_start'])."\">"; //there are dropdowns hidden for this!
		#print "<input type=hidden name=taken_end value=\"".he($_GET['taken_end'])."\">";
	} elseif ($start && $end) {
		
		$sql['wheres'][] = "imagetaken BETWEEN '$start' AND '$end'";

		$link = linktoself(array('delete'=>array('taken_start','taken_end')));
		print "<div class=\"filter\">Taken between <b>".getFormattedDate($start)."</b> and <b>".getFormattedDate($end)."</b>. [<a href=\"$link\">remove filter</a>]</div>";
	} elseif ($start) {
		
		$sql['wheres'][] = "imagetaken > '$start'";

		$link = linktoself(array('delete'=>array('taken_start','taken_end')));
		print "<div class=\"filter\">Taken after <b>".getFormattedDate($start)."</b>. [<a href=\"$link\">remove filter</a>]</div>";
	} elseif ($end) {
		
		$sql['wheres'][] = "imagetaken < '$end'";

		$link = linktoself(array('delete'=>array('taken_start','taken_end')));
		print "<div class=\"filter\">Taken before <b>".getFormattedDate($end)."</b>. [<a href=\"$link\">remove filter</a>]</div>";
	}
	
	$opt['filtered'] = 1;
} elseif (!empty($_GET['taken']) && preg_match('/^\d{2}$/',$_GET['taken'])) {
	$sql['wheres'][] = "MONTH(imagetaken) = ".dbQuote($_GET['taken']);
	//well, it saves having an array of months...
	if ($_GET['taken'] == '00') {
		$month = "unknown month";
	} else {
		$t = strtotime("2000-{$_GET['taken']}-01");
		$month = strftime("%B", $t);
	}
	$link = linktoself(array('delete'=>'taken'));
	print "<div class=\"filter\">Where <b>taken in $month</b>. [<a href=\"$link\">remove filter</a>]</div>";
	print "<input type=hidden name=taken value=\"".he($_GET['taken'])."\">";
	$opt['filtered'] = 1;

} elseif (!empty($_GET['taken']) && preg_match('/^\d{4}(-\d{2}|)(-\d{2}|)$/',$_GET['taken'])) {
	if (strlen($_GET['taken']) == 10) {
		$sql['wheres'][] = "imagetaken = ".dbQuote($_GET['taken']);
	} else {
		$sql['wheres'][] = "imagetaken LIKE ".dbQuote($_GET['taken'].'%');
	}
	$link = linktoself(array('delete'=>'taken'));
	print "<div class=\"filter\">Where <b>taken in {$_GET['taken']}</b>. [<a href=\"$link\">remove filter</a>]</div>";
	print "<input type=hidden name=taken value=\"".he($_GET['taken'])."\">";
	$opt['filtered'] = 1;

}

function getFormattedDate($input) {
        list($y,$m,$d)=explode('-', $input);
        $date="";
        if ($d>0) {
                if ($y>1970) {
                        //we can use strftime
                        $t=strtotime($input." 0:0:0");//stop a warning
                        $date=strftime("%A, %e %B, %Y", $t);   //%e doesnt work on WINDOWS!  (could use %d)
                } else {
                        //oh my!
                        $t=strtotime("2000-$m-$d");
                        $date=strftime("%e %B", $t)." $y";
                }
        } elseif ($m>0) {
                //well, it saves having an array of months...
                $t=strtotime("2000-$m-01");
                if ($y > 0) {
                        $date=strftime("%B", $t)." $y";
                } else {
                        $date=strftime("%B", $t);
                }
        } elseif ($y>0) {
                $date=$y;
        }
        return $date;
}


if (!empty($_GET['dd'])) {
	print "<pre>";
	print_r($sql);
	print "</pre>";
}

if (!empty($_GET['q'])) {
	//TODO invoke sphinx... 
}

